<?php

namespace frontend\modules\touch\controllers;

use yii\web\Controller;
use common\widgets\alipay\wappay\buildermodel\AlipayTradeWapPayContentBuilder;
use common\widgets\alipay\wappay\service\AlipayTradeService;
use backend\modules\home\models\Order;
use backend\modules\home\models\Vip;
use yii\myhelper\Response;
use Yii;

/**
 * Default controller for the `touch` module
 */
class OrderController extends Controller
{
    /**
     * Renders the index view for the module
     * @return string
     */
    public $enableCsrfValidation = false;

    public function actionIndex(){

    }

    /**
     * 创建订单
     */
    public function actionCreate(){
        $id = Yii::$app->request->post('charge_id');
        $pro = $this->getProductList($id);
        if(!$pro){
            Response::show('201','参数错误',[]);
        }

        if (Yii::$app->user->isGuest) {
            Response::show('202','未登录状态',[]);
        }

        // 年会员不让充值
        $vip_model = vip::findOne(['uid' => Yii::$app->user->identity->id]);
        if($vip_model){
            $exp = $vip_model->expire_time - time();
            if($exp > 2 * 365 * 24 * 3600){
                Response::show('201','您已是终生会员无需充值',[]);
            }
        }

        $uid = Yii::$app->user->identity->id;
        $model = new Order();
        $model->uid = $uid;
        $model->out_trade_no = (string)$this->getTradeNo();
        $model->pay_type = 'other';
        $model->subject = $pro['title'];
        $model->total_amount = $pro['price'];
        $model->status = 'unpay';
        $model->date = date('Y-m-d');
        $time = time();
        $model->create_at = $time;
        $model->update_at = $time;
        if($model->save()){
            Response::show('200','',[
                'price' => $model->total_amount,
                'title' => $pro['title'],
                'sn' => $model->out_trade_no,
            ]);
        }else{
            echo "<pre>";
            print_r($model->errors);exit;
        }
    }

    public function actionAliNotify(){

        $arr=$_POST;
        $config = $this->aliConfig();
        $alipaySevice = new AlipayTradeService($config);
        $alipaySevice->writeLog(var_export($_POST,true));
        $result = $alipaySevice->check($arr);

        /* 实际验证过程建议商户添加以下校验。
        1、商户需要验证该通知数据中的out_trade_no是否为商户系统中创建的订单号，
        2、判断total_amount是否确实为该订单的实际金额（即商户订单创建时的金额），
        3、校验通知中的seller_id（或者seller_email) 是否为out_trade_no这笔单据的对应的操作方（有的时候，一个商户可能有多个seller_id/seller_email）
        4、验证app_id是否为该商户本身。
        */
        if($result) {//验证成功
            /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
            //请在这里加上商户的业务逻辑程序代


            //——请根据您的业务逻辑来编写程序（以下代码仅作参考）——

            //获取支付宝的通知返回参数，可参考技术文档中服务器异步通知参数列表

            //商户订单号

            $out_trade_no = $_POST['out_trade_no'];

            //支付宝交易号

            $trade_no = $_POST['trade_no'];

            //交易状态
            $trade_status = $_POST['trade_status'];

            $body = $_POST['body'];


            if($_POST['trade_status'] == 'TRADE_FINISHED') {

                //判断该笔订单是否在商户网站中已经做过处理
                //如果没有做过处理，根据订单号（out_trade_no）在商户网站的订单系统中查到该笔订单的详细，并执行商户的业务程序
                //请务必判断请求时的total_amount与通知时获取的total_fee为一致的
                //如果有做过处理，不执行商户的业务程序
                //注意：
                //退款日期超过可退款期限后（如三个月可退款），支付宝系统发送该交易状态通知
            }
            else if ($_POST['trade_status'] == 'TRADE_SUCCESS') {
                //判断该笔订单是否在商户网站中已经做过处理
                //如果没有做过处理，根据订单号（out_trade_no）在商户网站的订单系统中查到该笔订单的详细，并执行商户的业务程序
                //请务必判断请求时的total_amount与通知时获取的total_fee为一致的
                //如果有做过处理，不执行商户的业务程序

                $data = $_POST;
                $extra = json_encode($data);
                $model = Order::findOne(['out_trade_no' => $out_trade_no, 'status' => 'unpay']);
                if($model){
                    $model->status = 'payed';
                    $model->update_at = time();
                    $model->callback = $extra;
                    $model->pay_type = 'alipay';
                    $model->transaction_id = (string)$trade_no;
                    if(!$model->save()){
                        $alipaySevice->writeLog(var_export($model->errors,true));
                    }else{
                        // 增加会员vip
                        if($model->subject == '日会员体验'){
                            $num = 1;
                        }elseif ($model->subject == '月会员体验'){
                            $num = 2;
                        }elseif ($model->subject == '终生会员体验'){
                            // 其实只有十年
                            $num = 365 * 10;
                        }else{
                            $num = 0;
                        }

                        $vip_model = new Vip();
                        $vip_select = $vip_model::findOne(['uid' => $model->uid]);
                        if($vip_select){
                            if($vip_select->expire_time < time()){
                                // 如果过期时间小于当前时间
                                $vip_select->expire_time = time() + $num*24*3600;
                            }else{
                                // 如果过期时间大于当前时间 就是还没过期
                                $vip_select->expire_time = $vip_select->expire_time + $num*24*3600;
                            }
                            $vip_select->save();
                        }else{
                            $vip_model->uid = $model->uid;
                            $vip_model->expire_time = time() + $num*24*3600;
                            $vip_model->create_at = time();
                            $vip_model->save();
                        }
                    }
                }else{
                    $alipaySevice->writeLog(var_export('my_error',true));
                }

                //注意：
                //付款完成后，支付宝系统发送该交易状态通知
            }
            //——请根据您的业务逻辑来编写程序（以上代码仅作参考)

            echo "success";		//请不要修改或删除

        }else {
            //验证失败
            echo "fail";	//请不要修改或删除

        }

    }

    public function actionPrePay(){
        if ( strpos($_SERVER['HTTP_USER_AGENT'], 'MicroMessenger') !== false ) {
            $str = $this->outHtml();
            return $str;
        }
        $sn = Yii::$app->request->get('sn');

        $select = Order::findOne(['out_trade_no' => $sn]);
        if(!$select){
            return $this->redirect('/touch/error?msgid=201');exit;
        }
        $this->layout = false;
        return $this->render('pre-pay',[
            'model' => $select,
        ]);
    }

    public function actionAlipay()
    {
        if ( strpos($_SERVER['HTTP_USER_AGENT'], 'MicroMessenger') !== false ) {
            $str = $this->outHtml();
            return $str;
        }

        $sn = Yii::$app->request->get('sn');

        $select = Order::findOne(['out_trade_no' => $sn]);
        if(!$select){
            return $this->redirect('/touch/error?msgid=201');exit;
        }

        $config = $this->aliConfig();
        //商户订单号，商户网站订单系统中唯一订单号，必填
        $out_trade_no = $select->out_trade_no;

        //订单名称，必填
        $subject = $select->subject;

        //付款金额，必填
        $total_amount = $select->total_amount;

        //商品描述，可空
        $body = $select->subject;

        //超时时间
        $timeout_express="1m";

        $payRequestBuilder = new AlipayTradeWapPayContentBuilder();//AlipayTradeWapPayContentBuilder();
        $payRequestBuilder->setBody($body);
        $payRequestBuilder->setSubject($subject);
        $payRequestBuilder->setOutTradeNo($out_trade_no);
        $payRequestBuilder->setTotalAmount($total_amount);
        $payRequestBuilder->setTimeExpress($timeout_express);

        $payResponse = new AlipayTradeService($config);//AlipayTradeService($config);
        $result=$payResponse->wapPay($payRequestBuilder,$config['return_url'],$config['notify_url']);
        return ;
    }

    public function actionAliReturn()
    {
        $config = $this->aliConfig();
        $arr = $_GET;
        $alipaySevice = new AlipayTradeService($config);
        $result = $alipaySevice->check($arr);

        /* 实际验证过程建议商户添加以下校验。
        1、商户需要验证该通知数据中的out_trade_no是否为商户系统中创建的订单号，
        2、判断total_amount是否确实为该订单的实际金额（即商户订单创建时的金额），
        3、校验通知中的seller_id（或者seller_email) 是否为out_trade_no这笔单据的对应的操作方（有的时候，一个商户可能有多个seller_id/seller_email）
        4、验证app_id是否为该商户本身。
        */
        if ($result) {//验证成功
            /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
            //请在这里加上商户的业务逻辑程序代码
            //——请根据您的业务逻辑来编写程序（以下代码仅作参考）——
            //获取支付宝的通知返回参数，可参考技术文档中页面跳转同步通知参数列表
            //商户订单号
            $out_trade_no = htmlspecialchars($_GET['out_trade_no']);
            //支付宝交易号
            $trade_no = htmlspecialchars($_GET['trade_no']);
            $total_amount = htmlspecialchars($_GET['total_amount']);
            //——请根据您的业务逻辑来编写程序（以上代码仅作参考）——
//            $identity = Yii::$app->session->get('identity');
//            return $this->render('ali-return',['data'=>$_GET,'identity'=>$identity]);
            return $this->redirect('/touch/default/index');
        } else {
            echo '验证失败';
        }
    }

    private function getTradeNo(){
        return date('YmdHis').mt_rand(10000,99999);
    }

    private function aliConfig(){
        $hosturl = Yii::$app->params['hosturl'];
        $config = array (
            //应用ID,您的APPID。
            'app_id' => "2017072707921323",

            //商户私钥
            'merchant_private_key' => "MIIEvQIBADANBgkqhkiG9w0BAQEFAASCBKcwggSjAgEAAoIBAQCcHjYjOh03sTw7ppNNs6oqGsMHKCPXBqdMd/PI3+Xsssyb49d61+A/TUEKRNEFEIjDciXroihzZ58NCpghV4+6C4osCZzaJrqTUmnS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KjhSYOz1zjJlftZ6SYnngWmV7YMVaB44Ys0VstL6fL6J+XQKBgBfp9ydGqBaZ6VrqpQ3Zgs+3uIEzy5O0A7Q0XD9VKZxgfbe05X8S1/CpVBgEiX1p4hskcnIvBKoYp9E/FsRPpsE0l6v0WG31H6eNLK2TKbG2pPAcS3p9TSfxYYDWc5gpWJGK6bWi5fk9TIF/76094nMa42cJa9v50aKWiXhIsHvpAoGAPB7OS4oBEjVS95g8S7boMT0qHy7kICjSadndWXV8A0PHDOMCjIayLqK3mD5aJB9FDpQYNz7moARiWTmgJytajVFMgADZT0/OeYltq3YgsCGyau7g994p5snj3J3458HqF1mBHOeCTfsVyarVfkwAb4m/iAyNM4+E9fev6Uibx0o=",

            //异步通知地址
            'notify_url' => $hosturl . "/touch/order/ali-notify",

            //同步跳转
            'return_url' => $hosturl . "/touch/order/ali-return",

            //编码格式
            'charset' => "UTF-8",

            //签名方式
            'sign_type'=>"RSA2",

            //支付宝网关
            'gatewayUrl' => "https://openapi.alipay.com/gateway.do",

            //支付宝公钥,查看地址：https://openhome.alipay.com/platform/keyManage.htm 对应APPID下的支付宝公钥。
            'alipay_public_key' => "MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAv4qPdn2Vyir9uMA0i8iCh/GCJEN4JYN6PGulIWAas1DV+0eQuTTCyR5P8jeBWprFeEJUrkN5AQdRhceRKV7J4kkdIHlIsUsLawQQl8UEhjrNDDDKTwkfvCiZa6FZ7HIPtdr2XQo5J0xIYO7P7Hrg8orfpqZU0jU14TjjYcHU0fmXIjtUqRvM8KFQ7JbqRPirMwsFMoEYvlhJ9tNrZJMkpDjJAXQCb8VsxsfO/ySLzvt5fHnJ0nbfqVGHKCgwSauC2Bz4ut45OsP1ZJA+SFdMAwesSJn2qhOfQ9Erx/G4eDvZLTDEaGy5kQr6J49AT5yo3rsWN7q6QMqjQEMjGUzCdQIDAQAB",
        );
        return $config;
    }

    private function getProductList($id){
        $product_list = [
            1 => [
                'title' => '日会员体验',
                'price' => '1.00',
            ],
            2 => [
                'title' => '月会员体验',
                'price' => '12.00',
            ],
            3 => [
                'title' => '终生会员体验',
                'price' => '99.00',
            ],
        ];
        if(isset($product_list[$id])){
            return $product_list[$id];
        }else{
            return false;
        }
    }

    public function outHtml(){
        $html = '<!DOCTYPE HTML>
<html>
<head>
    <meta charset="utf-8"
    ">
    <title>支付提示</title>
    <meta name="apple-mobile-web-app-capable" content="yes"/>
    <meta name="apple-mobile-web-app-status-bar-style" content="black"/>
    <meta name="format-detection" content="telephone=no"/>
    <meta name="format-detection" content="email=no"/>
    <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0, user-scalable=0"/>
    <style>
        *, :before, :after {
            -webkit-tap-highlight-color: rgba(0, 0, 0, 0)
        }

        body, div, dl, dt, dd, ul, ol, li, h1, h2, h3, h4, h5, h6, form, fieldset, legend, input, textarea, p, blockquote, th, td {
            margin: 0;
            padding: 0
        }

        table {
            border-collapse: collapse;
            border-spacing: 0
        }

        fieldset, img {
            border: 0
        }

        li {
            list-style: none
        }

        caption, th {
            text-align: left
        }

        q:before, q:after {
            content: ""
        }

        input:password {
            ime-mode: disabled
        }

        :focus {
            outline: 0
        }

        html, body {
            -webkit-touch-callout: none;
            touch-callout: none;
            -webkit-user-select: none;
            user-select: none;
            -webkit-tap-highlight-color: transparent;
            tap-highlight-color: transparent;
            height: 100%;
            margin: 0;
            padding: 0;
            text-align: center;
            font-size: 15px;
            font-weight: 300;
            font-family: "Helvetica Neue", Helvetica, Arial, "Lucida Grande", sans-serif
        }

        a {
            text-decoration: none
        }

        body {
            background: #F4F4F8
        }

        .weixin-tip {
            display: none;
            -webkit-box-sizing: border-box;
            box-sizing: border-box;
            position: absolute;
            top: 15px;
            right: 20px;
            width: 265px;
            padding: 55px 0 0;
            text-align: left;
            background: url() no-repeat right top;
            background-size: 45px 68px
        }

        .weixin-tip-img {
            display: none;
            padding: 110px 0 0
        }

        .weixin-tip-img::after {
            display: block;
            margin: 15px auto;
            content: \' \';
            background-size: cover
        }

        .weixin-tip-img.iphone::after {
            width: 150px;
            height: 150px;
            background-image: url()
        }

        .weixin-tip-img.android::after {
            width: 173px;
            height: 240px;
            background-image: url()
        }
    </style>
<meta name="poweredby" content="dragondean" />

</head>
<body>
<div class="J-weixin-tip weixin-tip">
    <div class="weixin-tip-content">
        请在菜单中选择在浏览器中打开,<br/>
        以完成支付
    </div>
</div>
<div class="J-weixin-tip-img weixin-tip-img"></div>

<div style=" padding:15px; text-align:center">
	<a href="/" style=" padding:10px 25px; border-radius:8px; background:rgb(116, 204, 146); color:#fff;">返回首页</a>
</div>
<script type="text/javascript" src="/js/alipay_in_wx.js"></script>
<script>
    if (location.hash.indexOf(\'error\') != -1) {
        alert(\'参数错误，请检查\');
    } else {
        var ua = navigator.userAgent.toLowerCase();
        var tip = document.querySelector(".weixin-tip");
        var tipImg = document.querySelector(".J-weixin-tip-img");
        if (ua.indexOf(\'micromessenger\') != -1) {
            tip.style.display = \'block\';
            tipImg.style.display = \'block\';
            if (ua.indexOf(\'iphone\') != -1 || ua.indexOf(\'ipad\') != -1 || ua.indexOf(\'ipod\') != -1) {
                tipImg.className = \'J-weixin-tip-img weixin-tip-img iphone\'
            } else {
                tipImg.className = \'J-weixin-tip-img weixin-tip-img android\'
            }
        } else {
            var getQueryString = function (url, name) {
                var reg = new RegExp("(^|\\?|&)" + name + "=([^&]*)(\\s|&|$)", "i");
                if (reg.test(url)) return RegExp.$2.replace(/\+/g, " ");
            };
            var param = getQueryString(location.href, \'goto\') || \'\';
            //location.href = param != \'\' ? _AP.decode(param) : \'pay.htm#error\';
        }
    }
</script>
<script src="//stat.loxn.cn/stat.js?fr=novel"></script>

</body>
</html>';
        return $html;
    }

}
